// ----------------------- 获取学员数据 -------------------------
function getList() {
  axios.get('/student/list').then(({data: {code, message, data}}) => {
    if (code === 0) {
      let html = ''
      data.forEach((item, index) => {
        html += `
          <tr>
            <th scope="row">${index + 1}</th>
            <td>${item.name}</td>
            <td>${item.age}</td>
            <td>${item.sex}</td>
            <td>${item.group}</td>
            <td>${item.phone}</td>
            <td>${item.salary}</td>
            <td>${item.truesalary}</td>
            <td>${item.province}</td>
            <td>
              <button type="button" data-id="${item.id}" class="btn btn-primary btn-sm edit">修改</button>
              <button type="button" data-id="${item.id}" class="btn btn-danger btn-sm del">删除</button>
            </td>
          </tr>
        `
      })
      qs('tbody').innerHTML = html
    }else {
      alert(message)
    }
  })
}
getList()


// ----------------------- 添加显示弹层 --------------------------
qs('#addBtn').onclick = function () {
  qs('#addModal').classList.add('show')
  qs('#backdrop').classList.add('show')
}
// 点击关闭按钮
qs('.btn-close').onclick = function () {
  qs('#addModal').classList.remove('show')
  qs('#backdrop').classList.remove('show')
}
// --------------------- 获取省 ---------------------
axios.get('/geo/province').then(({data}) => {
  let arr = ['<option selected value="">--省--</option>']
  data.forEach(item => {
    arr.push(`<option value="${item}">${item}</option>`)
  })
  qsAll('select[name=province]').forEach(item => item.innerHTML = arr.join(''))
})

// --------------------- 省切换的时候，选择市 ---------------------
qsAll('select[name=province]').forEach((item, i) => {
  item.onchange = function () {
    // 将县级选择框改为默认值
    qsAll('select[name=county]')[i].innerHTML = `<option selected value="">--县--</option>`
    // 获取到省的value值
    let pname = qsAll('select[name=province]')[i].value
    axios.get('/geo/city', {
      params: {
        pname
      }
    }).then(({data}) => {
      let arr = ['<option selected value="">--市--</option>']
      data.forEach(item => {
        arr.push(`<option value="${item}">${item}</option>`)
      })
      qsAll('select[name=city]')[i].innerHTML = arr.join('')
    })
  }
})
// --------------------- 市切换的时候，选择县 ---------------------
qsAll('select[name=city]').forEach((item, i) => {
  item.onchange = function () {
    // qs('select[name=county]').innerHTML = `<option selected value="">--县--</option>`
    let pname = qsAll('select[name=province]')[i].value
    let cname = qsAll('select[name=city]')[i].value
    axios.get('/geo/county', {
      params: {
        pname,
        cname
      }
    }).then(({data}) => {
      let arr = ['<option selected value="">--县--</option>']
      data.forEach(item => {
        arr.push(`<option value="${item}">${item}</option>`)
      })
      qsAll('select[name=county]')[i].innerHTML = arr.join('')
    })
  }
})

// -------------------- 添加完成 ----------------------------------
// 获取表单的值
qs('.add-form').onsubmit = function (e) {
  e.preventDefault()
  // 发送添加请求
  addStudentApi()
}
// 封装添加学员的接口
function addStudentApi() {
  axios.post('/student/add', getFormData('.add-form')).then(({data: {code, message}}) => {
    if (code === 0) {
      alert(message)
      qs('.add-form').reset()
      getList()
      qs('#addModal').classList.remove('show')
      qs('#backdrop').classList.remove('show')
    }
  }).catch(({error: {response: {data: {code, message}}}}) => {
    if (code === 1) {
      alert(message)
    }
  })
}

// ----------------------- 修改显示弹层 --------------------------
// 修改学员 / 删除学员(事件委托)
qs('tbody').onclick = function (e) {
  // 修改学员
  if (e.target.classList.contains('edit')) {
    const id = e.target.dataset.id
    axios.get('/student/one', {
      params: {
        id
      }
    }).then(({data: {code, data}}) => {
      if (code === 0) {
        const {id, name, sex, age, group, phone, salary, truesalary, province, city, county} = data
        qs('.update-form input[name=id]').value = id
        qs('.update-form input[name=name]').value = name
        qs('.update-form input[name=age]').value = age
        qs('.update-form input[name=phone]').value = phone
        qs('.update-form input[name=salary]').value = salary
        qs('.update-form input[name=truesalary]').value = truesalary

        // 属性选择器连写方式
        qs(`.update-form input[name=sex][value='${sex}']`).checked = true
        qs('.update-form select[name=group]').value = group

        qs('.update-form select[name=province]').value = province
        qs('.update-form select[name=city]').innerHTML = `<option value="${city}">${city}</option>`
        qs('.update-form select[name=county]').innerHTML = `<option value="${county}">${county}</option>`


        // 请求完成修改弹框显示
        qs('#updateModal').classList.add('show')
        qs('#backdrop').classList.add('show')
      }
    })
  }
  // 修改弹框隐藏
  qs('#closeEditBtn').onclick = function () {
    qs('#updateModal').classList.remove('show')
    qs('#backdrop').classList.remove('show')
  }
  // 删除学员
  if (e.target.classList.contains('del')) {
    if(!confirm('你确定要删除吗？')) return 
    const id = e.target.dataset.id
    axios.delete('/student/delete', {
      params: {
        id
      }
    }).then(({data: {code, message}}) => {
      if (code === 0) {
        alert(message)
        getList()
      }
      
    })
  }
}


// ------------------------- 修改学员 - 确认修改 ----------------------------
qs('#updateModal').onsubmit = function (e) {
  e.preventDefault()

  // 发送修改表单的请求
  axios.put('/student/update', getFormData('.update-form')).then(({data: {code, message}}) => {
    if(code === 0) {
      alert(message)
      getList()
      qs('#updateModal').classList.remove('show')
      qs('#backdrop').classList.remove('show')
    }
  })
}